<template>
  <el-dialog
      v-model="dialogVisible"
      title="编辑采购单"
      width="900px"
      :before-close="handleClose"
      class="PurchaseOrderEdit"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="PurchaseOrderEdit-form">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="订单编号" prop="orderNo">
            <div class="PurchaseOrderEdit-form-orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入订单编号"
                        class="PurchaseOrderEdit-form-orderNo-input"/>
              <el-button type="primary" class="PurchaseOrderEdit-form-orderNo-btn"
                         @click="generateOrderNo">随机生成
              </el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="form.supplierId" placeholder="请选择供应商" filterable clearable
                       class="PurchaseOrderEdit-form-input">
              <el-option v-for="s in supplierList" :key="s.id" :label="s.name" :value="s.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <!-- 下单日期只读显示，禁止修改 -->
          <el-form-item label="下单日期">
            <el-input :model-value="form.orderDate" disabled class="PurchaseOrderEdit-form-input" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input v-model="form.note" placeholder="可填写备注" class="PurchaseOrderEdit-form-input"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-alert title="当前暂不支持在此处修改明细项目。" type="info" :closable="false" class="PurchaseOrderEdit-tip"/>

    <el-table :data="items" border stripe class="PurchaseOrderEdit-table">
      <el-table-column type="index" label="序号" width="60" align="center"/>
      <el-table-column prop="code" label="商品编码" min-width="120" align="center"/>
      <el-table-column prop="name" label="商品名称" min-width="160" align="center"/>
      <el-table-column prop="unit" label="单位" width="100" align="center"/>
      <el-table-column prop="quantity" label="数量" width="120" align="center"/>
      <el-table-column prop="unitPrice" label="单价(¥)" width="120" align="center">
        <template #default="{row}">{{ formatMoney(row.unitPrice) }}</template>
      </el-table-column>
      <el-table-column prop="totalPrice" label="小计(¥)" width="140" align="center">
        <template #default="{row}">{{ formatMoney(row.totalPrice) }}</template>
      </el-table-column>
    </el-table>

    <div class="PurchaseOrderEdit-summary">
      <div class="PurchaseOrderEdit-summary-row">
        <div class="PurchaseOrderEdit-summary-label">合计金额：</div>
        <div class="PurchaseOrderEdit-summary-value">¥ {{ formatMoney(totalAmount) }}</div>
      </div>
    </div>

    <template #footer>
      <div class="PurchaseOrderEdit-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, watch, computed} from 'vue'
import {ElMessage} from 'element-plus'
import {getPurchaseOrder, updatePurchaseOrder} from '../../../../api/purchaseOrderApi.js'
import {listSuppliers} from '../../../../api/supplierApi.js'

const props = defineProps({visible: {type: Boolean, default: false}, orderId: {type: Number, default: null}})
const emits = defineEmits(['update:visible', 'success'])

const dialogVisible = ref(false)
const formRef = ref()
const form = reactive({id: null, orderNo: '', supplierId: null, orderDate: '', note: ''})
const items = ref([])
const supplierList = ref([])
const saving = ref(false)

// 移除 orderDate 校验（只读）
const rules = reactive({
  orderNo: [{required: true, message: '请输入订单编号', trigger: 'blur'}],
  supplierId: [{required: true, message: '请选择供应商', trigger: 'change'}]
})

watch(() => props.visible, (v) => {
  dialogVisible.value = v;
  if (v && props.orderId) {
    init()
  }
})
watch(dialogVisible, v => { if (!v) emits('update:visible', false) })

const init = async () => { await Promise.all([loadSuppliers(), loadDetail()]) }

const loadSuppliers = async () => {
  try { const res = await listSuppliers({condition: {}}); supplierList.value = res.list || [] } catch (e) { ElMessage.error('加载供应商失败') }
}
const loadDetail = async () => {
  try { const res = await getPurchaseOrder(props.orderId); if (res) { form.id = res.id; form.orderNo = res.orderNo; form.supplierId = res.supplierId; form.orderDate = res.orderDate; form.note = res.note; items.value = res.items || [] } } catch (e) { ElMessage.error('获取详情失败') }
}

const totalAmount = computed(() => items.value.reduce((acc, cur) => acc + Number(cur.totalPrice || 0), 0))

const handleClose = () => { dialogVisible.value = false }
const handleSave = async () => {
  try {
    await formRef.value?.validate();
    saving.value = true;
    // 不再提交 orderDate
    const payload = { id: form.id, orderNo: form.orderNo, supplierId: form.supplierId, note: form.note };
    await updatePurchaseOrder(payload);
    emits('success');
    dialogVisible.value = false;
  } catch (e) {
    // ignore
  } finally { saving.value = false }
}

const formatMoney = (v) => Number(v || 0).toFixed(2)
const generateOrderNo = () => { const randomCode = Math.floor(Math.random()*100000000).toString().padStart(8,'0'); form.orderNo = randomCode; ElMessage.success('已生成: '+randomCode) }
</script>

<style scoped lang="scss">
.PurchaseOrderEdit {
  &-form { padding: 16px 0; &-input { width: 100%; } &-orderNo { display: flex; align-items: center; gap: 8px; &-input { flex: 1; } &-btn { flex: 0 0 auto; } } }
  &-tip { margin-bottom: 16px; }
  &-table { width: 100%; margin-top: 8px; }
  &-summary { display: flex; justify-content: flex-end; padding: 16px 0; &-row { display: flex; gap: 8px; align-items: center; } &-label { font-size: 14px; color: #606266; } &-value { font-size: 16px; font-weight: 600; color: #303133; } }
  &-footer { display: flex; justify-content: flex-end; gap: 8px; }
}
</style>
